#include "types.h"
#include "stat.h"
#include "user.h"

/*
Similar to several built-in user space programs in xv6 (e.g., ls, grep, echo, etc.), you can
add your own user space programs to xv6.
Add a program called sanity. This program will fork 30 child processes. Each child
process will have a unique id (from 0 to 29) denoted by    . All even-numbered
processes will immediately activate the nice system call, reducing their priority.
Child processes code will print its     500 times and will then call exit. The parent
process will wait until its children exit, and then print the average waiting time, running
time and turnaround time of its children, followed by a printout of the waiting time,
running time and turnaround time of each child process
*/

#define PROC_COUNT 30
#define ITERATIONS 500

int getCidByPid(int pid, int * cids){
	int i;

	for (i = 0; i < PROC_COUNT; ++i) {
		if (cids[i]==pid){
			break;
		}
	}

	return i;
}

int
main(int argc, char *argv[])
{
	int i,j;
	//int cid;
	int cids[PROC_COUNT];
	int wtime[PROC_COUNT];
	int rtime[PROC_COUNT];
	int father;
	int avrgW;
	int avrgT;
	int avrgR;

	int tpid;
	int _wtime;
	int _rtime;
	int tmp_pid;


	avrgW = 0;
	avrgT = 0;
	avrgR = 0;

	father = getpid();
	//printf(1, "father pid:%d\n", father);

	for(i=0;i<PROC_COUNT;i++){
		if ((cids[i] = fork()) == 0){
			if (!(i % 2))
				nice();
			break;
		}

	}

	if (getpid() != father){
		// children do this
		for (j = 0; j < ITERATIONS; ++j) {
			printf(1, "cid %d\n", i);
		}
		exit();
	}
	else{
		//father section
		for (i = 0; i < PROC_COUNT; ++i) {
			if ((tpid=wait2(&_wtime,&_rtime)) <0){
				printf(2, "sanity error on wait2\n");
				exit();
			}
			tmp_pid = getCidByPid(tpid, cids);
			wtime[tmp_pid] = _wtime;
			rtime[tmp_pid] = _rtime;
		}
		for (i = 0; i < PROC_COUNT; ++i) {
			avrgW += wtime[i];
			avrgR += rtime[i];
		}
		avrgW = (avrgW)/PROC_COUNT;
		avrgR = (avrgR)/PROC_COUNT;
		avrgT = (avrgW + avrgR);

		printf(1, "Average waiting: %d, ", avrgW);
		printf(1, "running: %d, ", avrgR);
		printf(1, "turnaround: %d\n", avrgT);

		for (i = 0; i < PROC_COUNT; ++i) {
			printf(1, "cid %d, wtime=%d, rtime=%d, ttime%d\n", i, wtime[i], rtime[i], wtime[i]+rtime[i]);
		}

	}
	exit();

}
